/*
 * @Description: 自定义DOM覆盖物 - 继承DOMOverlay
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2023-06-26 17:08:14
 * @LastEditTime: 2023-06-27 09:56:37
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
 */
// 以下代码为基于DOMOverlay实现聚合点气泡
class LabelCluster extends TMap.DOMOverlay {
  constructor(options) {
    super(options)
    // 移动端touchmove事件执行时需禁止触发touchend
    this.enableClick = true
  }

  onInit (options) {
    this.content = options.content
    this.position = options.position
    this.coach_id = options.id
  }

  // 销毁时需要删除监听器
  onDestroy () {
    console.log("=====onDestroy")
    this.dom.removeEventListener('click', this.onClick)
    this.dom.removeEventListener('touchend', this.onTouchEnd)
    this.dom.removeEventListener('touchmove', this.onTouchMove)
    this.removeAllListeners()
  }

  // 点击事件
  onClick (e) {
    this.emit('click', e)
  }

  // 移动端触摸结束事件
  onTouchEnd (e) {
    // 移动端的触摸移动后禁止触发touchend事件
    if (!this.enableClick) {
      this.enableClick = true
      return
    }
    this.emit('touchend', e)
  }

  // 移动端触摸移动事件
  onTouchMove (e) {
    // 移动端的触摸移动后禁止触发touchend事件
    this.enableClick = false
    this.emit('touchmove', e)
  }

  // 创建气泡DOM元素
  createDOM () {
    var dom = document.createElement('img')
    dom.src = this.content
    // 设置DOM样式
    dom.style.cssText = 'position:absolute;top:0px;left:0px;width:60px;height:60px;object-fit: cover;border-radius:60px;border:2px solid #fff;'
    dom.setAttribute('data-id', this.coach_id)

    // 监听点击事件，实现zoomOnClick
    this.onClick = this.onClick.bind(this)
    this.onTouchEnd = this.onTouchEnd.bind(this)
    this.onTouchMove = this.onTouchMove.bind(this)
    // pc端注册click事件，移动端注册touchend事件
    dom.addEventListener('click', this.onClick)
    dom.addEventListener('touchend', this.onTouchEnd)
    dom.addEventListener('touchmove', this.onTouchMove)
    return dom
  }

  // 更新
  updateDOM () {
    if (!this.map) {
      return
    }
    // 经纬度坐标转容器像素坐标
    const pixel = this.map.projectToContainer(this.position)

    // 使文本框中心点对齐经纬度坐标点
    const left = pixel.getX() - this.dom.clientWidth / 2 + 'px'
    const top = pixel.getY() - this.dom.clientHeight / 2 + 'px'
    this.dom.style.transform = `translate(${left}, ${top})`

    this.emit('dom_updated')
  }
}
export default LabelCluster